﻿using System;
using CustomerContactSystem.Core.Model;

namespace CustomerContactSystem.WebForms.Enquiries.Avoidables {
    public partial class Create : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id")) {
                return;
            }

            EnquiryIdCaption.Text = Request.QueryString["id"];
            EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];
        }

        protected void SubmitAvoidableClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id")) {
                return;
            }

            if (AvoidableReason.Text.Trim().Length == 0) {
                SubmitAvoidableResultMessage.Text = "Please enter a reason for the enquiry being avoidable!";
                return;
            }

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (enquiry == null) {
                SubmitAvoidableResultMessage.Text = "Error enquiry not found!";
                return;
            }

            var avoidable = new EnquiryAvoidable
                {
                    ReasonAvoidable = AvoidableReason.Text
                };
            enquiry.AddAvoidable(avoidable);
            EnquiryRepository.Update(enquiry);

            Response.Redirect("~/Enquiries/View.aspx?id=" + enquiry.Id);
        }
    }
}